package priv.abadstring.study.haoke.webapi.manage.graphql;

import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 将 GraphQL 初始化后注入容器中
 *
 * @author aBadString
 * @date 2021-06-17 19:55:13
 */
@Component
public class GraphQLProvider {
    // @Autowired
    // private HouseResourcesManage houseResourcesManage;

    /** GOOD: 注入所有的 DataFetcherSpecification 实现类 */
    @Autowired
    private List<DataFetcherSpecification> dataFetcherList;

    @Bean
    public GraphQL graphQL() throws IOException {
        File file = ResourceUtils.getFile("classpath:haoke.graphqls");
        String sdl = FileUtils.readFileToString(file, "UTF-8");

        GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(
                // TypeDefinitionRegistry 是对查询的定义
                new SchemaParser().parse(sdl),
                // RuntimeWiring 是对数据源的定义
                RuntimeWiring.newRuntimeWiring()
                        .type(
                            "HaokeQuery",
                            // (builder) -> builder.dataFetcher(
                            //     "HouseResources",
                            //     (args) -> {
                            //         Long id = ((Integer) args.getArgument("id")).longValue();
                            //         // 查询数据库
                            //         return this.houseResourcesManage.getById(id);
                            //     }
                            // )
                            (builder) -> {
                                // 像 builder 添加一堆的 DataFetcher
                                this.dataFetcherList.forEach((dataFetcherSpecification) ->
                                    builder.dataFetcher(
                                        dataFetcherSpecification.fieldName(),
                                        dataFetcherSpecification::dataFetcher
                                    )
                                );
                                return builder;
                            }
                        )
                        .build());

        return GraphQL.newGraphQL(schema).build();
    }
}
